using System;
using UnityEngine;
using EchoFramework;

/// <summary>
/// 计算器界面
/// </summary>
public class CalculatorView : UIViewBase
{
    private RectTransform mainRectTrans;
    private EchoButton bgBtn;
    private EchoText showTxt;
    private EchoButton deleteBtn;
    private EchoButton oneKeyBtn;
    private EchoButton twoKeyBtn;
    private EchoButton threeKeyBtn;
    private EchoButton addKeyBtn;
    private EchoButton fourKeyBtn;
    private EchoButton fiveKeyBtn;
    private EchoButton sixKeyBtn;
    private EchoButton reduceKeyBtn;
    private EchoButton sevenKeyBtn;
    private EchoButton eightKeyBtn;
    private EchoButton nineKeyBtn;
    private EchoButton multiKeyBtn;
    private EchoButton zeroKeyBtn;
    private EchoButton doubleZeroKeyBtn;
    private EchoButton equalOrConfirmKeyBtn;
    private EchoText equalOrConfirmKeyBtnTxt;
    private EchoButton divideKeyBtn;

    /// <summary>
    /// 计算符号数组
    /// </summary>
    private readonly string[] symbolArr = new[] {"+", "-", "*", "/"};

    /// <summary>
    /// 阵营
    /// </summary>
    private CampEnum camp = CampEnum.None;

    /// <summary>
    /// 对应的Disk位置
    /// </summary>
    private int index = 0;

    /// <summary>
    /// Disk类型
    /// </summary>
    private DiskEnum diskEnum = DiskEnum.None;

    /// <summary>
    /// 是否是确认状态
    /// </summary>
    private bool isComfirmStatus;

    /// <summary>
    /// 计算器显示的内容
    /// </summary>
    private string showValue;

    /// <summary>
    /// 是否存在符号
    /// </summary>
    private bool isExistSymbol;

    /// <summary>
    /// 首次打开计算器时，如果没默认带计算符号，当输入数字时，直接覆盖内容
    /// </summary>
    private bool isNumNeedCover;

    public override void OnAwake()
    {
        base.OnAwake();
        mainRectTrans = prefabBinder.Find("MainRectTrans").GetComponent<RectTransform>();
        bgBtn = prefabBinder.Find("BgBtn").GetComponent<EchoButton>();
        bgBtn.onClick.AddListener(OnClickBgBtn);
        showTxt = prefabBinder.Find("ShowTxt").GetComponent<EchoText>();
        deleteBtn = prefabBinder.Find("DeleteBtn").GetComponent<EchoButton>();
        deleteBtn.onClick.AddListener(OnClickDeleteBtn);
        oneKeyBtn = prefabBinder.Find("OneKeyBtn").GetComponent<EchoButton>();
        oneKeyBtn.onClick.AddListener(OnClickOneKeyBtn);
        twoKeyBtn = prefabBinder.Find("TwoKeyBtn").GetComponent<EchoButton>();
        twoKeyBtn.onClick.AddListener(OnClickTwoKeyBtn);
        threeKeyBtn = prefabBinder.Find("ThreeKeyBtn").GetComponent<EchoButton>();
        threeKeyBtn.onClick.AddListener(OnClickThreeKeyBtn);
        addKeyBtn = prefabBinder.Find("AddKeyBtn").GetComponent<EchoButton>();
        addKeyBtn.onClick.AddListener(OnClickAddKeyBtn);
        fourKeyBtn = prefabBinder.Find("FourKeyBtn").GetComponent<EchoButton>();
        fourKeyBtn.onClick.AddListener(OnClickFourKeyBtn);
        fiveKeyBtn = prefabBinder.Find("FiveKeyBtn").GetComponent<EchoButton>();
        fiveKeyBtn.onClick.AddListener(OnClickFiveKeyBtn);
        sixKeyBtn = prefabBinder.Find("SixKeyBtn").GetComponent<EchoButton>();
        sixKeyBtn.onClick.AddListener(OnClickSixKeyBtn);
        reduceKeyBtn = prefabBinder.Find("ReduceKeyBtn").GetComponent<EchoButton>();
        reduceKeyBtn.onClick.AddListener(OnClickReduceKeyBtn);
        sevenKeyBtn = prefabBinder.Find("SevenKeyBtn").GetComponent<EchoButton>();
        sevenKeyBtn.onClick.AddListener(OnClickSevenKeyBtn);
        eightKeyBtn = prefabBinder.Find("EightKeyBtn").GetComponent<EchoButton>();
        eightKeyBtn.onClick.AddListener(OnClickEightKeyBtn);
        nineKeyBtn = prefabBinder.Find("NineKeyBtn").GetComponent<EchoButton>();
        nineKeyBtn.onClick.AddListener(OnClickNineKeyBtn);
        multiKeyBtn = prefabBinder.Find("MultiKeyBtn").GetComponent<EchoButton>();
        multiKeyBtn.onClick.AddListener(OnClickMultiKeyBtn);
        zeroKeyBtn = prefabBinder.Find("ZeroKeyBtn").GetComponent<EchoButton>();
        zeroKeyBtn.onClick.AddListener(OnClickZeroKeyBtn);
        doubleZeroKeyBtn = prefabBinder.Find("DoubleZeroKeyBtn").GetComponent<EchoButton>();
        doubleZeroKeyBtn.onClick.AddListener(OnClickDoubleZeroKeyBtn);
        equalOrConfirmKeyBtn = prefabBinder.Find("EqualOrConfirmKeyBtn").GetComponent<EchoButton>();
        equalOrConfirmKeyBtn.onClick.AddListener(OnClickEqualOrConfirmKeyBtn);
        equalOrConfirmKeyBtnTxt = prefabBinder.Find("EqualOrConfirmKeyBtnTxt").GetComponent<EchoText>();
        divideKeyBtn = prefabBinder.Find("DivideKeyBtn").GetComponent<EchoButton>();
        divideKeyBtn.onClick.AddListener(OnClickDivideKeyBtn);
    }

    public override void OnStart(params object[] objs)
    {
        base.OnStart(objs);
        SwitchEqualOrConfirm(true); //默认显示为确定文字
        if (objs.Length < 4)
        {
            GameLogger.LogError("传入参数数量错误，自动关闭界面！");
            CloseWindow();
            return;
        }

        camp = (CampEnum) objs[0];
        index = (int) objs[1];
        diskEnum = (DiskEnum) objs[2];
        showValue = objs[3].ToString();
        SafeShowValue();
        isNumNeedCover = true;
        if (camp == CampEnum.Player2)
        {
            mainRectTrans.localRotation = Quaternion.Euler(180f, 180f, 0);
        }
        if (objs.Length >= 5)
        {
            string symbol = objs[4].ToString();
            SafeShowValue(symbol);
            isNumNeedCover = false;
        }
    }

    /// <summary>
    /// 切换"="与确定状态
    /// </summary>
    /// <param name="isConfirmStatus">是否显示确定状态</param>
    private void SwitchEqualOrConfirm(bool isConfirmStatus)
    {
        this.isComfirmStatus = isConfirmStatus;
        if (isConfirmStatus)
        {
            equalOrConfirmKeyBtnTxt.LoadLang("Common_Confirm"); //确定
            equalOrConfirmKeyBtnTxt.fontSize = 150;
        }
        else
        {
            equalOrConfirmKeyBtnTxt.LoadLang("=");
            equalOrConfirmKeyBtnTxt.fontSize = 200;
        }
    }

    /// <summary>
    /// 安全的显示文本
    /// </summary>
    /// <param name="value">输入的value</param>
    /// <param name="isAddOperator">是否为增加操作</param>
    private void SafeShowValue(string value = "", bool isAddOperator = true)
    {
        if (string.IsNullOrEmpty(value) && isAddOperator)
        {
            bool _isDigit = IsDigit(showValue);
            SwitchEqualOrConfirm(_isDigit);
            showTxt.text = showValue;
            isExistSymbol = !_isDigit;
            return;
        }

        if (isAddOperator) //增加操作
        {
            if (IsCalcuatorSymbol(value)) //传入的是计算符号
            {
                if (isExistSymbol || showValue.Length == 0) return; //不能出现多个计算符号或者第一个文本是计算符号
                showValue += value;
            }
            else //数字或“=”
            {
                if (value.Equals("="))
                {
                    if (isExistSymbol)
                    {
                        string lastStr = showValue[showValue.Length - 1].ToString();
                        if (IsCalcuatorSymbol(lastStr)) return;
                        //开始计算
                        string num1Str = string.Empty;
                        string num2Str = string.Empty;
                        string symbol = string.Empty;
                        for (int i = 0; i < showValue.Length; i++)
                        {
                            string str = showValue[i].ToString();
                            if (IsCalcuatorSymbol(str))
                            {
                                symbol = str;
                                continue;
                            }

                            if (string.IsNullOrEmpty(symbol))
                            {
                                num1Str += str;
                            }
                            else
                            {
                                num2Str += str;
                            }
                        }

                        if (string.IsNullOrEmpty(num1Str) || string.IsNullOrEmpty(symbol) ||
                            string.IsNullOrEmpty(num2Str))
                        {
                            return;
                        }
                        else
                        {
                            float num1 = Convert.ToSingle(num1Str);
                            float num2 = Convert.ToSingle(num2Str);
                            float ret = 0;
                            switch (symbol)
                            {
                                case "+":
                                    ret = num1 + num2;
                                    break;
                                case "-":
                                    ret = num1 - num2;
                                    break;
                                case "*":
                                    ret = num1 * num2;
                                    break;
                                case "/":
                                    if (num2 != 0)
                                        ret = num1 / num2;
                                    break;
                            }

                            ret = Mathf.Ceil(ret);
                            int intRet = (int) ret;
                            intRet = intRet < 0 ? 0 : intRet;
                            showValue = intRet.ToString();
                        }
                    }
                }
                else
                {
                    if (isNumNeedCover)
                    {
                        showValue = value;
                    }
                    else
                    {
                        showValue = showValue + value;
                    }
                }
            }

            isNumNeedCover = false;
        }
        else //减少操作
        {
            if (showValue.Length > 0)
            {
                showValue = showValue.Substring(0, showValue.Length - 1);
                isNumNeedCover = false;
            }
        }

        bool isDigit = IsDigit(showValue);
        isExistSymbol = !isDigit;
        SwitchEqualOrConfirm(isDigit);
        showTxt.text = showValue;
    }

    /// <summary>
    /// 是否是计算符号
    /// </summary>
    /// <param name="value">传入的字符</param>
    private bool IsCalcuatorSymbol(string value)
    {
        foreach (string symbolStr in symbolArr)
        {
            if (value.Equals(symbolStr))
                return true;
        }

        return false;
    }

    /// <summary>
    /// 是否是数字
    /// </summary>
    /// <param name="value">传入的字符串</param>
    private bool IsDigit(string value)
    {
        foreach (char ch in value)
        {
            if (ch < '0' || ch > '9')
            {
                return false;
            }
        }

        return true;
    }

    private void OnClickBgBtn()
    {
        CloseWindow();
    }

    private void OnClickDeleteBtn()
    {
        SafeShowValue("", false);
    }

    private void OnClickOneKeyBtn()
    {
        SafeShowValue("1");
    }

    private void OnClickTwoKeyBtn()
    {
        SafeShowValue("2");
    }

    private void OnClickThreeKeyBtn()
    {
        SafeShowValue("3");
    }

    private void OnClickAddKeyBtn()
    {
        SafeShowValue("+");
    }

    private void OnClickFourKeyBtn()
    {
        SafeShowValue("4");
    }

    private void OnClickFiveKeyBtn()
    {
        SafeShowValue("5");
    }

    private void OnClickSixKeyBtn()
    {
        SafeShowValue("6");
    }

    private void OnClickReduceKeyBtn()
    {
        SafeShowValue("-");
    }

    private void OnClickSevenKeyBtn()
    {
        SafeShowValue("7");
    }

    private void OnClickEightKeyBtn()
    {
        SafeShowValue("8");
    }

    private void OnClickNineKeyBtn()
    {
        SafeShowValue("9");
    }

    private void OnClickMultiKeyBtn()
    {
        SafeShowValue("*");
    }

    private void OnClickZeroKeyBtn()
    {
        SafeShowValue("0");
    }

    private void OnClickDoubleZeroKeyBtn()
    {
        SafeShowValue("00");
    }

    private void OnClickEqualOrConfirmKeyBtn()
    {
        if (isComfirmStatus)
        {
            if (string.IsNullOrEmpty(showValue))
            {
                CloseWindow();
                return;
            }
            
            int retValue = Convert.ToInt32(showValue);
            GameLogger.LogYellow("结果为：" + retValue);
            EventManager.Instance.Execute(EventTypeEnum.RefreshDisk, camp, index, diskEnum, retValue);
            CloseWindow();
        }
        else
        {
            SafeShowValue("=");
        }
    }

    private void OnClickDivideKeyBtn()
    {
        SafeShowValue("/");
    }
}